package com.smooth.site.sx.pc.jifen.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.smooth.common.site.common.enums.SiteCodeEnums;
import com.smooth.common.site.common.excep.SiteException;
import com.smooth.common.site.common.persistence.Page;
import com.smooth.common.site.common.utils.IntegerUtils;
import com.smooth.dao.gen.BizGoodsMapper;
import com.smooth.dao.gen.bean.BizGoods;
import com.smooth.dao.gen.bean.BizGoodsExample;
import com.smooth.sys.pc.vo.ListRsp;

@Component
public class PcGoodsService {
	Logger log = LoggerFactory.getLogger(PcGoodsService.class);
	@Autowired
	BizGoodsMapper bizGoodsMapper;
	public ListRsp<BizGoods> queryGoodsList(int limit,int offset){
		BizGoodsExample bizGoodsExample = new BizGoodsExample();
		bizGoodsExample.setOrderByClause(" create_date desc ");
		bizGoodsExample.setPage(new Page(offset/limit,limit));
		List<BizGoods> glist = bizGoodsMapper.selectByExample(bizGoodsExample);
		
		ListRsp<BizGoods> lrsp = new ListRsp<BizGoods>();
		lrsp.setDatalist(glist);
		lrsp.setTsize(bizGoodsMapper.countByExample(bizGoodsExample));
		return lrsp;
	}
	
	public BizGoods queryGoodsDetail(String id){
		return bizGoodsMapper.selectByPrimaryKey(id);
	}
	
	public void subGoodsStock(String id,Integer num) {
		BizGoods bizGoods = bizGoodsMapper.selectByPrimaryKey(id);
		if(IntegerUtils.add(bizGoods.getStockNum(), num)<0) {
			throw new SiteException(SiteCodeEnums.STOCK_NOT_ENOUGH, bizGoods.getGoodTitle()+"");
		}
		
		BizGoods bizGoodsRecord = new BizGoods();
		bizGoodsRecord.setId(id);
		bizGoodsRecord.setStockNum(IntegerUtils.add(bizGoods.getStockNum(), -num));
		
		int optNum = bizGoodsMapper.updateByPrimaryKeySelective(bizGoodsRecord);
		if(optNum==1) {
			log.info("更新库存成功【"+id+"】剩余【"+IntegerUtils.add(bizGoods.getStockNum(), num)+"】 消耗【"+num+"】");
		}
	}
}
